/*
 * UdpSessionManager.cpp
 *
 *  Created on: 27/08/2011
 *      Author: george
 */

#include "udpsessionmanager.h"
#include "udpsession.h"
#include <cstdlib>

#include <arpa/inet.h>
UdpSessionManager::UdpSessionManager() {}

bool UdpSessionManager::add(ip_hdr_t* ip,  udp_hdr_t* udp){
	unsigned session_pos  = this->getSession(ip->ip_src, ip->ip_dst, ntohs(udp->source), ntohs(udp->dest), (u_int8_t)ip->ip_p);
	UdpSession* udp_session =  this->session[session_pos];
	udp_session->add(udp);
	return true;
}

unsigned UdpSessionManager::getSession(in_addr src, in_addr dst, u_int16_t src_port, u_int16_t dst_port, u_int8_t protocol){

	unsigned pos = 0;

	bool check_from_client_src = false;
	bool check_from_client_dst = false;

	bool check_from_server_src = false;
	bool check_from_server_dst = false;

	while (pos < this->session.size() )
	{
		// verifica no caso de o pacote ter sido enviado do cliente

		check_from_client_src = ( this->session[pos]->src.s_addr == src.s_addr && this->session[pos]->src_port == src_port );
		check_from_client_dst = ( this->session[pos]->dst.s_addr == dst.s_addr && this->session[pos]->dst_port == dst_port );

		if ( check_from_client_src && check_from_client_dst )
		{
			return pos;
		}

		// verifica no caso do pacote ter sido enviado do servidor
		check_from_server_src = ( this->session[pos]->src.s_addr == dst.s_addr && this->session[pos]->src_port == dst_port );
		check_from_server_dst = ( this->session[pos]->dst.s_addr == src.s_addr && this->session[pos]->dst_port == src_port );

		if ( check_from_server_src && check_from_server_dst )
		{
			return pos;

		}

		pos++;

	}


	this->session.push_back(new UdpSession(src, dst, src_port, dst_port, protocol));

	return this->session.size() -1;
}

UdpSessionManager::~UdpSessionManager(){

}

